﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections;

namespace Greyhound
{
    class Reactor_Engine_HTML
    {
        HTML_TagControl tagcontroller = new HTML_TagControl();
        HTML_Storage storage = new HTML_Storage();
        public void HTMLLoader()
        {
            FileStream fs = File.OpenRead(@"c:\Greyhound\page.html");
            StreamReader reader = new StreamReader(fs);
            String line = null;
            int linenumber = 1;
            while ((reader.ReadLine()) != null)
            {
                HTMLParse(line, linenumber);
                linenumber++;
            }
        }
        public void HTMLParse(String line, int linenumber)
        {
            List<int> positionlist = new List<int>();
            for (int i = 0; i < line.Length; i++)
            {
                if (line[i] == '<' || line[i] == '>')
                {
                    positionlist.Add(i);
                }
            }
            int numberoftags = positionlist.Count();
            int tagposition1 = 0;
            int tagposition2 = 0;
            int tagnamearraycounter = 0;
            List<HTML_Line_Cache> cache = new List<HTML_Line_Cache>();
            // Only 1 < per line exception will be here!
            for (int x = 0; x < numberoftags; x+=2)
            {
                char[] tagname = new char[500]; 
                tagposition1 = positionlist[x];
                tagposition2 = positionlist[x++];
                if (line[positionlist[x]] == '<' && line[positionlist[x++]] == '>')
                {
                    for (int y = tagposition1++; y < tagposition2; y++)
                    {
                        tagname[tagnamearraycounter] = line[y];
                        tagnamearraycounter++;
                    }
                    String tagnamestring = new String(tagname);
                    HTML_Tag Tag = null;
                    Tag = tagcontroller.findTag(tagnamestring);
                    if (Tag == null)
                    {
                        goto endofloop;
                    }
                    tagcontroller.setSwitch(Tag.getName());
                    cache.Add(new HTML_Line_Cache(tagcontroller.activeTags(), tagposition1));
                }
            endofloop:
                tagnamearraycounter = 0;
            }
            storage.store(cache, linenumber);
        }

    }
}
